import Vue from "vue";
import Router from "vue-router";
import { getRouter } from "@/router/router.js";
import axios from "axios";

// 启用路由
Vue.use(Router);

const routes = [
  {
    path: "/",
    name: "",
    redirect: "/business/dbsjcwz",
    hidden: true,
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login"),
    hidden: true,
    meta: {
      title: "登录",
    },
  },
  {
    path: "/reloadPage",
    name: "reload-page",
    component: () => import("@/views/reload.vue"),
  },
];

const router = new Router({
  mode: "hash",
  routes,
});

// 路由拦截器
router.beforeEach((to, from, next) => {
  if (to.name != 'login') { //如果不是登录页面
    if (localStorage.getItem('userInfo')) {
      const urlParams = new URLSearchParams(window.location.search);
      const tokenFromUrl = urlParams.get('token') || '';
      if(tokenFromUrl) {
        const newUrl = window.location.origin + window.location.pathname; // 获取没有参数的 URL
        window.history.replaceState({}, document.title, newUrl); // 修改浏览器地址栏
      }
      if (routes.length < 5) {
        let menuList = localStorage.getItem('menuList')
        if (menuList) {
          let menu = JSON.parse(menuList)
          const newRoutes = routes;
          Promise.all([getRouter(menu, newRoutes)]).then((result) => {
            const newRouter = new Router({
              mode: "hash",
              routes: result[0],
            });
            router.matcher = newRouter.matcher;
            router.push({ path: to.path })
          });
        }
      } else {
        next()
      }
    }   //已登录就执行跳转
    else next({ name: 'login' })   //否则跳转到登录页面
  } else { //如果是登录页面
    if (localStorage.getItem('userInfo')) next({ path: '/' }) //已登录就跳转到首页
    else next()  //否则正常进入登录页面
  }
});
export default router;
export { routes };
